package com.iwhalecloud.citybrain.flow.platform.manager.application.utils;

import org.apache.commons.collections4.MapUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author cheng.huaxing
 * @date 2019-02-18
 */
public class HttpClientUtils {

    private HttpClientUtils() {}

    /**
     * http get请求
     *
     * @param url
     * @return
     */
    public static String httpGet(String url, Map<String, String> headMap) {
        String responseContent = null;
        Map<String, Object> responseMap = httpGetWithStatusCode(url, headMap);
        if (MapUtils.isNotEmpty(responseMap)) {
            responseContent = String.valueOf(responseMap.get("response"));
        }
        return responseContent;
    }

    /**
     * http get请求
     *
     * @param url
     * @return
     */
    private static Map<String, Object> httpGetWithStatusCode(String url, Map<String, String> headMap) {
        Map<String, Object> responseMap = new HashMap<>(16);
        String responseContent = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpclient.execute(httpGet);
            setGetHead(httpGet, headMap);
            try {
                int statusCode = response.getStatusLine().getStatusCode();
                responseMap.put("statusCode", statusCode);
                HttpEntity entity = response.getEntity();
                responseContent = getRespString(entity);
                responseMap.put("response", responseContent);

                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseMap;
    }


    /**
     * http的post请求
     *
     * @param url
     * @param body
     * @return
     */
    public static String httpPost(String url, String body, Map<String, String> headMap) {
        String responseContent = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            setPostHead(httpPost, headMap);
            setPostParams(httpPost, body);
            try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                responseContent = getRespString(entity);
                EntityUtils.consume(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return responseContent;
    }

    /**
     * 设置POST的参数
     *
     * @param httpPost
     * @param body
     * @throws Exception
     */
    private static void setPostParams(HttpPost httpPost, String body) throws Exception {
        StringEntity stringEntity = new StringEntity(body);
        stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);
    }

    /**
     * 设置http的HEAD
     *
     * @param httpPost
     * @param headMap
     */
    private static void setPostHead(HttpPost httpPost, Map<String, String> headMap) {
        if (headMap != null && headMap.size() > 0) {
            Set<String> keySet = headMap.keySet();
            for (String key : keySet) {
                httpPost.addHeader(key, headMap.get(key));
            }
        }
    }

    /**
     * 设置http的HEAD
     *
     * @param httpGet
     * @param headMap
     */
    private static void setGetHead(HttpGet httpGet, Map<String, String> headMap) {
        if (headMap != null && headMap.size() > 0) {
            Set<String> keySet = headMap.keySet();
            for (String key : keySet) {
                httpGet.addHeader(key, headMap.get(key));
            }
        }
    }

    /**
     * 将返回结果转化为String
     *
     * @param entity
     * @return
     * @throws Exception
     */
    private static String getRespString(HttpEntity entity) throws Exception {
        if (entity == null) {
            return null;
        }
        InputStream is = entity.getContent();
        StringBuilder strBuf = new StringBuilder();
        byte[] buffer = new byte[4096];
        int r = 0;
        while ((r = is.read(buffer)) > 0) {
            strBuf.append(new String(buffer, 0, r, StandardCharsets.UTF_8));
        }
        return strBuf.toString();
    }
}
